import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-outsource-page',
  templateUrl: './outsource-page.component.html',
  styleUrls: ['./outsource-page.component.css']
})
export class OutsourcePageComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      userType: {
        validators: {
          notEmpty: {
            message: '请选择用户类型'
          }
        }
      },
      provinceId: {
        validators: {
          notEmpty: {
            message: '请选择省份'
          }
        }
      },
      cityId: {
        validators: {
          notEmpty: {
            message: '请选择城市'
          }
        }
      },
      cantonalId: {
        validators: {
          notEmpty: {
            message: '请选择市区'
          }
        }
      },
      companyName: {
        validators: {
          notEmpty: {
            message: '请输入团队名称'
          },
          stringLength: {
            max: 30,
            message: '团队名称30字以内'
          },
          remote: {
            message: '此团队名称已存在，请重新添加',
            url: config.BaseURL + 'outsourcingTeam/checkCompanyNameIsRepeat.html',
            data: function (validator) {
              return {
                id: validator.getFieldElements('companyName').attr('companyId')
              }
            }
          }
        }
      }
    }
  }
  page: any = {
    id: '',
    roleId: '',
    roleName: '',
    userType: '',
    userTypeName: '',
    provinceId: '',
    cityId: '',
    cantonalId: '',
    companyName: '',
    email: '',
    tel: '',
    linkmen: '',
    address: '',
    remark: '',
    installInRoyalty: '',
    installOutRoyalty: '',
    createDate: '',
    createUser: '',
    createUserName: ''
    // parentId: '#',
    // parentName: '外包(根目录)'
  }
  areaData: any = [] //省市县数据
  provinceNameArr: any = [] //省数据
  cityNameArr: any = [] //城市数据
  townNameArr: any = [] //县数据
  page_title: string = '新增'
  pageType: string = 'new'
  roleList: any = [] //角色list
  curPage: number = 0 //缓存页码使用
  rowId = null
  timer: any
  companyList: any //公司数据
  userTypeArr: any = [] //用户类型类型
  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.rowId = queryParams.id
      this.pageType = queryParams.type
      this.curPage = queryParams.nowPage
    })
  }
  //省份change回调事件
  provinceChange(e) {
    this.cityNameArr = []
    this.townNameArr = []
    this.page.provinceId = e
    for (let item of this.areaData) {
      if (this.page.provinceId === item.parentId) {
        this.cityNameArr.push(item)
      }
    }
  }
  //城市change回调事件
  cityChange(e) {
    this.townNameArr = []
    this.page.cityId = e
    for (let item of this.areaData) {
      if (this.page.cityId === item.parentId) {
        this.townNameArr.push(item)
      }
    }
  }
  townChange(e) {
    this.page.cantonalId = e
  }
  timeOut: any = ''
  //from表单提交
  onSubmit() {
    if (!this.page.roleId) {
      this.jsonApiService.message('请选择角色')
      return
    }
    if (this.pageType === 'new') {
      $('#companyForm').bootstrapValidator('validate') //开启验证
      let isValid = $('#companyForm').data('bootstrapValidator').isValid() //验证是否通过
      if (isValid) {
        this.updata()
      }
    } else if (this.pageType === 'updata') {
      this.timer = setTimeout(() => {
        $('#companyForm').bootstrapValidator('validate') //开启验证
        let isValid = $('#companyForm').data('bootstrapValidator').isValid() //验证是否通过
        if (isValid) {
          this.updata()
        }
      }, 500)
    }
  }
  telChange() {
    if (!this.page.tel) {
      this.page.tel = ''
    }
  }
  //from表单提交
  updata() {
    clearTimeout(this.timer)
    let reqdata: string = '',
      url: string = ''
    const page: Record<string, any> = this.deepClone(this.page)

    const tempInstallInRoyalty: any = page.installInRoyalty ? parseFloat(page.installInRoyalty) : null
    page.installInRoyalty = tempInstallInRoyalty ? tempInstallInRoyalty.toFixed(2) * 100 : null

    const tempInstallOutRoyalty: any = page.installOutRoyalty ? parseFloat(page.installOutRoyalty) : null
    page.installOutRoyalty = tempInstallOutRoyalty ? tempInstallOutRoyalty.toFixed(2) * 100 : null

    for (let item in page) {
      if (page[item] || page[item] === 0) {
        if (!reqdata) {
          reqdata += item + '=' + page[item]
        } else {
          reqdata += '&' + item + '=' + page[item]
        }
      }
    }
    url = 'outsourcingTeam/addOutsourcingTeam.html'

    this.jsonApiService.http(url, reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.router.navigate(['/system/outsource'], {
          queryParams: {
            nowPage: this.curPage
          }
        })
      }
    })
  }
  //返回资源列表页
  goBack() {
    this.router.navigate(['/system/outsource'], {
      queryParams: {
        nowPage: this.curPage
      }
    })
  }
  //深拷贝浅拷贝
  deepClone(obj) {
    let objClone = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === 'object') {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          //判断ojb子元素是否为对象，如果是，递归复制
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this.deepClone(obj[key])
          } else {
            //如果不是，简单复制
            objClone[key] = obj[key]
          }
        }
      }
    }
    return objClone
  }
  //拉取省市县数据
  initdata() {
    return new Promise(
      function (resolve, reject) {
        this.jsonApiService.http('company/regionList.html', null).subscribe(data => {
          if (data.message) {
            this.areaData = data.data
            for (let item of this.areaData) {
              if (item.level === 2) {
                this.provinceNameArr.push(item)
              }
            }
            resolve()
          } else {
            this.jsonApiService.message(data.message)
            reject()
          }
        })
      }.bind(this)
    )
  }
  ngOnInit() {
    const that = this
    that.initUserTypedata()
    //初始化from表单
    that.initdata().then(() => {
      that.initAllRole().then(() => {
        if (that.pageType === 'updata') {
          that.page_title = '编辑'
          let reqdata = 'id=' + this.rowId

          this.jsonApiService.http('outsourcingTeam/outsourcingTeamInfo.html', reqdata).subscribe(data => {
            if (data.success) {
              for (let item in this.page) {
                this.page[item] = data.data[item]
              }
              var temCity = data.data
              if (temCity) {
                this.provinceChange(temCity.provinceId == null ? '' : temCity.provinceId)
                this.cityChange(temCity.cityId == null ? '' : temCity.cityId)
                this.page.provinceId = temCity.provinceId == null ? '' : temCity.provinceId
                this.page.cityId = temCity.cityId == null ? '' : temCity.cityId
                this.page.cantonalId = temCity.cantonalId == null ? '' : temCity.cantonalId
              }
              if (data.data.roleId) {
                that.select2Role().then(() => {
                  $('#roleSelect2').val(data.data.roleName).change()
                  var str = $("<span class='select2-selection__rendered'>" + data.data.roleName + '</span>')
                  $('#select2-roleSelect2-container').empty()
                  $('#select2-roleSelect2-container').attr('title', data.data.roleName)
                  $('#select2-roleSelect2-container').prepend(str)
                })
              }
              this.page.installInRoyalty = data.data.installInRoyalty ? data.data.installInRoyalty / 100 : null
              this.page.installOutRoyalty = data.data.installOutRoyalty ? data.data.installOutRoyalty / 100 : null
            } else {
              this.jsonApiService.message(data.message)
            }
          })
        } else {
          that.page_title = '新增'
          that.select2Role().then(() => {
            $('#roleSelect2').val('').change()
            var str = $("<span class='select2-selection__rendered'></span>")
            $('#select2-roleSelect2-container').empty()
            $('#select2-roleSelect2-container').attr('title', '')
            $('#select2-roleSelect2-container').prepend(str)
          })
          return
        }
      })
    })
  }

  //初始化select2 角色配置
  select2Role() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
        System.import('assets/js/select2-zh-CN.js').then(() => {
          $('#roleSelect2')
            .select2({
              language: 'zh-CN',
              placeholder: '请选择',
              allowClear: true,
              data: that.roleList //为Select添加数据
            })
            .on('select2:select', function (e) {
              var data = e.params.data
              $('#roleSelect2').val(data.id).change()
              that.page.roleId = data.id
              that.page.roleName = data.text
            })
          resolve(true)
        })
      })
    })
  }

  //拉取角色数据
  initAllRole() {
    var that = this
    //修改为展示所有角色的数据
    let reqdata = 'userType=1'
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('outsourcingTeam/getRole.html', reqdata).subscribe(data => {
        if (data.success) {
          var roleList = data.data
          var selectdata = []
          for (var i = 0; i < roleList.length; i++) {
            var obj = {
              id: roleList[i].id,
              text: roleList[i].name
            }
            selectdata[i] = obj
          }
          that.roleList = selectdata
          resolve(true)
        } else {
          this.jsonApiService.message(data.message)
          reject()
        }
      })
    })
  }
  //拉取角色类型数据
  initUserTypedata() {
    this.jsonApiService.http('outsourcingTeam/getUserType.html', {}).subscribe(data => {
      if (data.message) {
        this.userTypeArr = data.data
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  userTypeChange(value) {
    this.page.userType = value
    for (let i = 0; i < this.userTypeArr.length; i++) {
      if (this.userTypeArr[i].userType == value) {
        this.page.userTypeName = this.userTypeArr[i].userTypeName
      }
    }
  }
}
